<?php

namespace MoChat\App\Statistic\Action\Call;

use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Rbac\Middleware\PermissionMiddleware;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;

/**
 * 呼叫汇总统计折线图
 * @Controller
 */
class CallBroken extends AbstractAction
{

    private function generationTime($list): array
    {
        if (empty($list)) {
            $startDate = date('Y-m-01');
            $endDate = date('Y-m-01', strtotime('+1 month'));
        } else {
            $startDate = reset($list)->times;
            $endDate = end($list)->times;
        }
        $startTime = strtotime($startDate);
        $endTime = strtotime($endDate);
        $timeRage = [];
        while (true) {
            if ($startTime > $endTime) {
                break;
            }
            $date = date('Y-m-d', $startTime);
            $timeRage[] = $date;
            $startTime += 86400;
        }
        return $timeRage;
    }

    private function formatData($list,$data): array
    {
        $timeRage = $this->generationTime($list);
        $value = [];
        $list = !empty($list) ? array_column($list, null, 'times') : [];
        foreach ($timeRage as $time) {
            //类型:1总通话数;2呼出量;3呼出时长;4呼出接通量
            if ($data['type']==1){
                $value[] = $list[$time]->totalNumber ?? 0;
                continue;
            }
            if ($data['type']==2){
                $value[] = $list[$time]->callOutNumber ?? 0;
                continue;
            }
            if ($data['type']==3){
                $value[] = $list[$time]->callOutDuration ?? 0;
                continue;
            }
            if ($data['type']==4){
                $value[] = $list[$time]->callOutAnswerNumber ?? 0;
            }
        }
        return [
            'brokenKey' => $timeRage,
            'brokenValue' => $value,
        ];
    }

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @RequestMapping(path="/dashboard/statisticCall/broken", methods="GET")
     */
    public function handle()
    {
        $user = user();
        // 判断用户绑定企业信息
        if (!isset($user['corpIds']) || count($user['corpIds']) !== 1) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '未选择登录企业，不可操作');
        }
        $data = $this->request->all();
        $data['startTime'] = $data['startTime'] ?? date('Y-m-01 00:00:00');
        $data['endTime'] = $data['endTime'] ?? date('Y-m-d H:i:s');
        //呼出总时长
        $list = $this->callRecord($data);
        $list || $list = collect([]);
        $list = $list->toArray();
        return $this->formatData($list,$data);
    }

    private function callRecord($data): \Hyperf\Utils\Collection
    {
        return Db::table('work_employee as employee')
            ->join('user as user', 'user.id', '=', 'employee.log_user_id')
            ->leftJoin('work_department as dept', 'dept.id', '=', 'employee.main_department_id')
            ->leftJoin('call_record as record', 'record.user_id', '=', 'user.id')
            ->when(!empty($data['deptId']), function ($query) use ($data) {
                $query->where('dept.id', $data['deptId']);
            })
            ->when(!empty($data['employeeId']), function ($query) use ($data) {
                $query->where('employee.id', '=', $data['employeeId']);
            })
            ->when(!empty($data['startTime']) && !empty($data['endTime']), function ($query) use ($data) {
                $query->whereBetween('record.created_time', [$data['startTime'], $data['endTime']]);
            })
            ->select([
                Db::raw("DATE_FORMAT(mc_record.`created_time`, '%Y-%m-%d') AS `times`"),
                Db::raw('COUNT(*) as totalNumber'),//总通话数
                Db::raw('COUNT(mc_record.call_type="out" or null) as callOutNumber'),//呼出总量
                Db::raw('SUM(if(mc_record.call_type="out",call_duration,0)) as callOutDuration'),//呼出总时长
                Db::raw('COUNT((mc_record.call_duration > 0 && mc_record.call_type="out") or null) as callOutAnswerNumber'),//呼出接听量
            ])->groupBy([
                Db::raw("DATE_FORMAT(mc_record.`created_time`, '%Y-%m-%d')")
            ])->orderBy('record.created_time', 'asc')->get();
    }
}
